<template>
  <div class="app-container">
    <!-- 顶部 -->
    <el-row
      :gutter="24"
      class="el-btn"
      style="margin-bottom:15px"
    >
      <el-col :span="12">
        <el-button
          type="primary"
          @click="dialog = true"
        >新增</el-button>
        <el-button type="danger">高级搜索</el-button>
      </el-col>
      <el-col :span="12">
        <el-input
          placeholder="请输入内容"
          v-model="input"
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="onSearch"
          ></el-button>
        </el-input>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="examlist"
      :border="true"
      id="table"
      max-height="450"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        fixed
        type="selection"
        width="60"
        align="center"
      >
      </el-table-column>
      <el-table-column
        fixed
        type="index"
        label="序号"
        width="60"
        :resizable="false"
        align="center"
        sortable
      >
      </el-table-column>
      <el-table-column
        prop="title"
        label="题目"
        width="300"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="type"
        label="分类"
        width="160"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="作者"
        width="160"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="date"
        label="发布时间"
        width="260"
        align="center"
        sortable
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="300"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="middle"
            @click="onLook(scope.row)"
          >
            详情
          </el-button>
          <el-button
            type="warning"
            size="middle"
            @click="onEdit(scope.row)"
          >
            修改
          </el-button>
          <el-button
            @click="deleteRow(scope.row.id)"
            type="danger"
            size="middle"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top:26px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="dialog"
      :before-close="handleClose"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
      size="60%"
      :show-close="false"
    >
      <div class="demo-drawer__content">
        <el-form
          :model="form"
          :disabled="look"
          label-position="right"
        >
          <el-form-item
            label="题目："
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              rows="1"
              style="width:666px"
              v-model="form.title"
              placeholder="请填写题目"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="分类："
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="form.cid"
              placeholder="请选择类别"
            >
              <el-option
                v-for="(item,index) in classify"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="选项："
            :label-width="formLabelWidth"
          >
            <div
              id="optionsBox"
              v-for="(item,index) in form.options"
              :key="index"
              style="display:flex"
            >
              <el-checkbox-group
                v-model="form.answers"
                style="margin-right:12px"
              >
                <el-checkbox
                  :label="optionsArr[index]"
                  name="options"
                  v-model="item.checked"
                >
                </el-checkbox>
              </el-checkbox-group>
              <el-input
                type="textarea"
                rows="1"
                v-model="item.value"
              ></el-input>

              <!-- + & - 出现在最后一个选项之后 -->
              <div
                class="add-options"
                v-if="!look && index==(form.options.length-1)"
              >
                <el-button
                  type="success"
                  icon="el-icon-plus"
                  circle
                  @click="addOpt"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-minus"
                  circle
                  @click="remOpt"
                ></el-button>
              </div>
            </div>
          </el-form-item>

          <el-form-item
            label="答案："
            :label-width="formLabelWidth"
          >
            {{ form.answers }}
          </el-form-item>

          <el-form-item
            label="提示："
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              v-model="form.tips"
              rows="1"
              style="width:666px"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button
            v-if="!look"
            type="primary"
            @click="closeDrawer"
          >确 定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";

export default {
  data() {
    return {
      input: "",
      title: "新增题库页面",
      form: {
        options: [
          {
            index: "A",
            value: "",
            checked: false,
          },
          {
            index: "B",
            value: "",
            checked: false,
          },
          {
            index: "C",
            value: "",
            checked: false,
          },
          {
            index: "D",
            value: "",
            checked: false,
          },
        ],
        answers: [],
      },
      dialog: false, // 打开抽屉
      formLabelWidth: "80px",
      look: false, // 详情
      ids: [],
      optionsAry: [],
      optionsNub: 3,
    };
  },
  async mounted() {
    await this.getExamlist();
    await this.getTableData();
    await this.getInfo();
  },
  methods: {
    ...mapActions("exam", [
      "getExamlist",
      "sendExam",
      "removeList",
      "deletExam",
    ]),
    ...mapActions("user", ["getInfo"]),
    ...mapActions("msbd", ["getTableData"]),
    ...mapMutations("exam", [
      "SET_CURRENT",
      "SET_PAGESIZE",
      "SET_SEARCH",
      "SET_ORDER",
    ]),

    // 表格 -多选
    handleSelectionChange(arr) {
      this.ids = arr.map((v) => {
        return v.id;
      });
    },

    // 修改
    onEdit(data) {
      data.options =
        typeof data.options == "object"
          ? data.options
          : JSON.parse(data.options);
      data.answers = JSON.parse(data.answers);
      this.form = { ...data };
      this.title = "修改题库页面";
      this.dialog = true;
    },
    // 详情
    onLook(data) {
      data.options =
        typeof data.options == "object"
          ? data.options
          : JSON.parse(data.options);
      this.look = true;
      this.form = data;
      this.title = "题库详情页面";
      this.dialog = true;
    },
    // 移除
    deleteRow(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deletExam(id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },

    // 分页
    handleSizeChange(val) {
      this.SET_PAGESIZE(val);
      this.getExamlist();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.SET_CURRENT(val);
      this.getExamlist();
      console.log(`当前页: ${val}`);
    },

    // 搜索
    onSearch() {
      this.SET_SEARCH(this.input);
      this.getExamlist();
    },

    // 抽屉
    handleClose() {
      this.cancelForm();
    },
    cancelForm() {
      this.look = false;
      this.dialog = false;
      this.form = {
        options: [
          {
            index: "",
            value: "",
            checked: false,
          },
        ],
        answers: [],
      };
      clearTimeout(this.timer);
    },
    closeDrawer() {
      if (!this.look) {
        this.$confirm("确定要提交表单吗？")
          .then((_) => {
            if (this.form.id) {
              this.addFn("修改");
            } else {
              this.form.uid = this.info.id;
              this.addFn("增加");
            }
            this.cancelForm();
          })
          .catch((_) => {});
      } else {
        this.cancelForm();
      }
    },
    // 封Z
    addFn(text) {
      this.form.options = JSON.stringify(this.form.options);
      this.form.answers = JSON.stringify(this.form.answers);
      this.sendExam(this.form);
      this.$message({
        message: `您已${text}成功`,
        type: "success",
      });
    },

    // 抽屉 -加减
    addOpt() {
      if (this.form.options.length >= 6) {
        this.$message({
          message: "已达到选项上限！别点了!",
          type: "warning",
        });
        return;
      } else {
        this.form.options.push({
          checked: false,
          index: this.optionsArr[this.form.options.length],
          value: "",
        });
      }
    },
    remOpt() {
      if (this.form.options.length <= 4) {
        this.$message.error("已达到最小项数！再点就没了！");
        return;
      } else {
        this.form.options.pop();
      }
    },
  },
  computed: {
    ...mapState("exam", ["examlist", "total", "currentPage", "pageSize"]),
    ...mapState("msbd", ["classify"]),
    ...mapState("user", ["info"]),

    optionsArr() {
      for (var i = 0; i < 26; i++) {
        this.optionsAry.push(String.fromCharCode(65 + i));
      }
      return this.optionsAry;
    },
  },
  watch: {
    form() {},
  },
};
</script>

<style scoped>
.el-table_1_column_4 > .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-input-group__prepend,
.el-select,
.el-select--medium {
  width: 100px;
}

.demo-drawer__footer {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.el-select,
.el-input__inner {
  width: 120px;
}

.add-options {
  position: absolute;
  left: 380px;
  bottom: 0;
}

#optionsBox {
  width: 360px;
}
</style>

<style>
.el-drawer__header > span {
  outline: none ;
  border: 0 ;
}

#table {
  height: calc(100vh - 272px);
}
</style>